package cn.iocoder.yudao.module.promotion.coupon.mq;

import cn.hutool.extra.spring.SpringUtil;
import cn.iocoder.yudao.module.api.member.user.message.MemberUserCreateMessage;
import cn.iocoder.yudao.module.api.trade.scan.dto.ScanOrderDTO;
import cn.iocoder.yudao.module.api.trade.scan.message.ScanOrderPaidMessage;
import cn.iocoder.yudao.module.promotion.coupon.service.CouponRecordService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.event.EventListener;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;

/**
 * 优惠券 事件消费者
 *
 * @author owen
 */
@Component
@Slf4j
public class CouponConsumer {

    @EventListener
    @Async // Spring Event 默认在 Producer 发送的线程，通过 @Async 实现异步
    public void onMessage(MemberUserCreateMessage message) {
        log.info("[promotion/coupon][onMessage][用户创建事件({})]", message);
        SpringUtil.getBean(CouponRecordService.class).takeCouponByRegister(message.getUserId());
    }

    @EventListener
    @Async // Spring Event 默认在 Producer 发送的线程，通过 @Async 实现异步
    public void onMessage(ScanOrderPaidMessage message) {
        ScanOrderDTO order = message.getOrder();
        log.info("[promotion/coupon][onMessage][扫码订单付款完成事件({})]", order.getTradeNo());
        if (order.getCouponId() != null && order.getCouponId() > 0) {
            log.debug("[promotion/coupon][onMessage][扫码订单付款使用优惠券({})抵扣]", order.getCouponId());
            SpringUtil.getBean(CouponRecordService.class).useCoupon(order.getCouponId(), order.getUserId(), order.getId());
        }
    }

}
